"""
verify create agent with knowledge API - copy from source agent
test if source_agent_id parameter works correctly
"""
import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

import logging
from src.llm.hiagent_app.services.agent_knowledge_service import AgentKnowledgeService
from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig

# configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def test_create_without_copy():
    """test create agent without copying (baseline test)"""
    logger.info("=" * 60)
    logger.info("Test 1: Create agent without copying (baseline)")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent_no_copy",
            knowledge_name="test_knowledge_no_copy",
            agent_description="test without copy",
            workspace_id=workspace_id
        )
        logger.info(f"SUCCESS - Agent ID: {agent_id}, Knowledge ID: {knowledge_id}")

        # cleanup
        logger.info("Cleaning up test resources...")
        service._cleanup_resources(agent_id, knowledge_id, workspace_id)
        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def test_create_with_copy():
    """test create agent by copying from source agent"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 2: Create agent by copying from source agent")
    logger.info("=" * 60)

    service = AgentKnowledgeService()
    workspace_id = HiAgentConfig.DEFAULT_WORKSPACE_ID
    source_agent_id = "d3tjsrvi96maquv5k8v0"  # source agent ID provided by user

    logger.info(f"Source Agent ID: {source_agent_id}")

    try:
        agent_id, knowledge_id = service.create_agent_with_knowledge(
            agent_name="test_agent_copied",
            knowledge_name="test_knowledge_copied",
            agent_description="test copied from source",
            workspace_id=workspace_id,
            source_agent_id=source_agent_id
        )
        logger.info(f"SUCCESS - Agent ID: {agent_id}, Knowledge ID: {knowledge_id}")
        logger.info(f"Agent was copied from source: {source_agent_id}")

        # cleanup
        logger.info("Cleaning up test resources...")
        service._cleanup_resources(agent_id, knowledge_id, workspace_id)
        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        logger.error("NOTE: If error mentions config incomplete, make sure source agent is properly configured and published")
        return False


def test_api_request_model():
    """test API request model structure with source_agent_id"""
    logger.info("\n" + "=" * 60)
    logger.info("Test 3: API request model with source_agent_id")
    logger.info("=" * 60)

    try:
        from src.routers.hiagent_center import CreateAgentWithKnowledgeRequest

        # test with source_agent_id
        request = CreateAgentWithKnowledgeRequest(
            agent_name="test_agent",
            knowledge_name="test_knowledge",
            agent_description="test description",
            workspace_id="test_workspace_id",
            source_agent_id="d3tjsrvi96maquv5k8v0"
        )

        logger.info(f"Request model created successfully:")
        logger.info(f"  agent_name: {request.agent_name}")
        logger.info(f"  knowledge_name: {request.knowledge_name}")
        logger.info(f"  agent_description: {request.agent_description}")
        logger.info(f"  workspace_id: {request.workspace_id}")
        logger.info(f"  source_agent_id: {request.source_agent_id}")

        return True
    except Exception as e:
        logger.error(f"FAILED - Error: {str(e)}")
        return False


def main():
    """main test function"""
    logger.info("Starting create-with-knowledge copy functionality verification")
    logger.info("=" * 60)

    results = {
        "test_api_request_model": test_api_request_model(),
        "test_create_without_copy": test_create_without_copy(),
        "test_create_with_copy": test_create_with_copy()
    }

    logger.info("\n" + "=" * 60)
    logger.info("Test Results Summary")
    logger.info("=" * 60)
    for test_name, result in results.items():
        status = "PASS" if result else "FAIL"
        logger.info(f"{test_name}: {status}")

    all_passed = all(results.values())

    logger.info("\n" + "=" * 60)
    if all_passed:
        logger.info("ALL TESTS PASSED")
        logger.info("=" * 60)
        logger.info("Copy functionality is working correctly:")
        logger.info("1. Can create agent normally without copying")
        logger.info("2. Can create agent by copying from source agent")
        logger.info("3. API request model accepts source_agent_id parameter")
        logger.info("4. Copied agent gets updated with new name and description")
    else:
        logger.info("SOME TESTS FAILED")
        logger.info("=" * 60)
        logger.info("Please review the error messages above")
        logger.info("")
        logger.info("Common issues:")
        logger.info("- Source agent must be properly configured (model, prompts, etc)")
        logger.info("- Source agent should ideally be published")
        logger.info("- Ensure source_agent_id exists in the workspace")


if __name__ == "__main__":
    main()
